package webservices.mobile;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

import com.cb.common.util.ConfigUtil;

	public class  MoblieUtil {
	
		private static String genRealUrl(String mobile, String message)
					throws UnsupportedEncodingException {
			
			String circle=ConfigUtil.getInstance().getProperty("circle");
			String pwd=ConfigUtil.getInstance().getProperty("pwd");
			String sendUrl=ConfigUtil.getInstance().getProperty("send.url");
			
				StringBuilder sb = new StringBuilder(sendUrl);
			
				sb.append("?circle="+circle);
				sb.append("&pwd="+pwd);
				sb.append("&mobile="+mobile);
				sb.append("&service=");
				String msg = URLEncoder.encode(message, "gb2312");
				sb.append("&message=" + msg);
				return sb.toString();
			}

			public static int sendSms(String mobile, String message) {

				URL url = null;
				InputStream in = null;
				BufferedReader br = null;
				String resultStr = null;
				try {
					   /*System.setProperty(   "proxySet",   "true"   );
				        System.setProperty(   "proxyHost",   "10.123.74.137");
				        System.setProperty(   "proxyPort",   "808"   );*/


					String realUrl = genRealUrl(mobile, message);
					System.out.println("发送短信URL" + realUrl);
					url = new URL(realUrl);
					URLConnection conn = url.openConnection();
					in =  conn.getInputStream();
					br = new BufferedReader(new InputStreamReader(in));
					StringBuilder sb = new StringBuilder();
					String line = null;
					while ((line = br.readLine()) != null) {
						sb.append(line);
					}
					resultStr = sb.toString().trim();
				} catch (MalformedURLException e) {
					System.out.println("URL格式错误!");
					e.printStackTrace();
					return -1;
				} catch (IOException e) {
					System.out.println("IO错误!");
					e.printStackTrace();
					return -1;
				} finally {
					if (br != null) {
						try {
							br.close();
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
					if (in != null) {
						try {
							in.close();
						} catch (IOException e) {
							e.printStackTrace();
						}
					}

				}
				if (resultStr.equals("0")) {
					System.out.println("发送短信 手机号:" + mobile + "   内容:" + message
							+ "  成功 " + resultStr);
				} else {
					System.out.println("发送短信 手机号:" + mobile + "   内容:" + message
							+ "  失败 " + resultStr);
				}

				int result = -1;
				try {
					result = Integer.parseInt(resultStr);
				} catch (Exception e) {
				}
				return result;
			}

			public static void main(String[] args) throws Exception {

				
				int result = sendSms("13718939492","36;NM8836;NM8836;NM8836;NM8836");
				System.out.println(result);
		}

	}

